package com.it.gw.modules.water.activity.shoubu

import LoginVo
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.it.common.bean.MapDataBean
import com.it.common.utils.DisplayUtil
import com.it.common.utils.GsonUtils
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.common.utils.tr
import com.it.data.manager.AppCacheManager
import com.it.data.network.req.ShouBuRecordDto
import com.it.data.network.req.UploadFileDto
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.data.PhotoBean
import com.it.gw.databinding.ActivityShoubuItemDetailBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.manager.DictionariesManager.DPC_ENG_GRAD_1
import com.it.gw.manager.DictionariesManager.MAIN_BUILD_GRAD
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.adapter.SelectPhotoAdapter
import com.it.gw.modules.water.viewmodel.WaterViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.io.File

//首部详情
class ShouBuItemDetailActivity : BaseActivity<ActivityShoubuItemDetailBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()
    private val photos = mutableListOf<PhotoBean>()
    private var selectPhotoAdapter: SelectPhotoAdapter? = null
    companion object {
        const val TAG = "ShouBuItemDetailActivity"
    }


    override fun initObserver() {
        waterViewModel.shouBuRecordDtoDetailLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(TAG, "pumpRecordDtoDetailLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                setDetailView(it.data!!)
            }

        }
        waterViewModel.insertLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_SHORT).show()
            }

        }

    }

    private fun setDetailView(data: ShouBuRecordDto) {


        binding.lttd.setText(data.lttd.tr()) // 泵站纬度
        binding.gcbh.setText(data.gcbh.tr()) // 工程编号
        binding.gqmc.setText(data.gqmc.tr()) // 灌区名称
        binding.sztcdm.setText(data.sztcdm.tr()) // 所在团场
        binding.sbmc.setText(data.sbmc.tr()) // 首部名称
        binding.szqdmc.setText(data.szqdmc.tr()) // 所在渠道名称
//        binding.sblx.setText(data.sblx) // 首部类型
        //首部类型
        binding.sblx.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.sblxList,
                code = data.sblx.tr()
            )
        )

//        binding.gcdb.setText(data.gcdb) // 工程等别
        //工程等别
        binding.gcdb.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(DPC_ENG_GRAD_1),
                code = data.gcdb.tr()
            )
        )
      //  binding.zyjzwjb.setText(data.zyjzwjb) // 主要建筑物级别

        //主要建筑物级别
        binding.zyjzwjb.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD),
                code = data.zyjzwjb.tr()
            )
        )
        binding.zjll.setText(data.zjll.tr()) // 装机流量(m3/s)
        binding.sjyc.setText(data.sjyc.tr()) // 设计扬程(m)
        binding.zjgl.setText(data.zjgl.tr()) // 装机功率(kW)
        binding.sbsl.setText(data.sbsl.tr()) // 水泵数量(台)
        binding.glfmj.setText(data.glfmj.tr()) // 管理房面积(㎡)
        binding.gdcd.setText(data.gdcd.tr()) // 管道长度(m)
        binding.gcrw.setText(data.gcrw.tr()) // 工程任务
        binding.kzggmj.setText(data.kzggmj.tr()) // 控制灌溉面积(亩)
        binding.ngPsl.setText(data.ngPsl.tr()) // 年供、排水量(m3)
        binding.trsysj.setText(data.trsysj.tr()) // 投入使用时间(年月)
        binding.gjsj.setText(data.gjsj.tr()) // 改建时间(年月)
        binding.gldwmc.setText(data.gldwmc.tr()) // 管理单位名称
        binding.lgtd.setText(data.lgtd.tr()) // 经度
        binding.note.setText(data.note.tr()) // 更新备注
        binding.opinion.setText(data.opinion.tr())
        //显示文件图片
        if (data.fileList.isNotEmpty()) {
            val list =
                data.fileList?.map { PhotoBean(filePath = "", id = it.id, url = it.filePath) }
            if (list != null) {
                photos.addAll(list)
                selectPhotoAdapter?.notifyDataSetChanged()
            }
        }
    }


    override fun initListener() {
        binding.rlUpload.setOnClickListener {
            showPicSelect { type ->
                if (type == 1) {
                    takePhoto { path ->
                        Log.d(TAG, "onBindViewHolder: takePhoto ${it}")
                        uploadFile(path)

                    }
                } else if (type == 2) {
                    pickMedia { path ->
                        Log.d(TAG, "onBindViewHolder: pickMedia ${it}")
                        uploadFile(path)
                    }
                }

            }

        }
        binding.lgtd.setOnClickListener {
            startLocation()
        }
        binding.lttd.setOnClickListener {
            startLocation()
        }

        binding.btnSave.setOnClickListener {
            insertShouBuRecord()

        }

        binding.sblx.setOnClickListener {
            DictionariesManager.sblxList.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.sblx.text =
                            DictionariesManager.sblxList[index].ITEMNAME

                    })
            }
        }

        binding.gcdb.setOnClickListener {
            DictionariesManager.dictionariesMap.get(DPC_ENG_GRAD_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.gcdb.text =
                            DictionariesManager.dictionariesMap.get(DPC_ENG_GRAD_1)!![index].ITEMNAME

                    })
            }
        }

        binding.zyjzwjb.setOnClickListener {
            DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.zyjzwjb.text =
                            DictionariesManager.dictionariesMap.get(MAIN_BUILD_GRAD)!![index].ITEMNAME

                    })
            }
        }




        binding.trsysj.setOnClickListener {
            showYearMonthPickerDialog(selectDateAction = {
                binding.trsysj.text = it
            })
        }
        binding.gjsj.setOnClickListener {
            showYearMonthPickerDialog(selectDateAction = {
                binding.gjsj.text = it
            })
        }


    }
    private fun uploadFile(path: String?) {
        lifecycleScope.launch {
            runCatching {
                ProgressDialog.show(this@ShouBuItemDetailActivity)
                val uploadFileDtoList = mutableListOf<UploadFileDto>()
                val file = File(path)
                uploadFileDtoList.add(UploadFileDto(file = file, fileName = file.name))
                val res = waterViewModel.upload(uploadFileDtoList)
                ProgressDialog.hide()
                if (res.success == true) {
                    photos.add(PhotoBean(filePath = path, id = res.data))
                    selectPhotoAdapter?.notifyDataSetChanged()
                } else {
                    Toast.makeText(
                        this@ShouBuItemDetailActivity,
                        "上传文件失败${res.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }.onFailure {
                ProgressDialog.hide()
                Toast.makeText(
                    this@ShouBuItemDetailActivity,
                    "上传文件失败${it.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
        }

    }
    private fun insertShouBuRecord() {
        ProgressDialog.show(this)
        val loginVo = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)
        val dto = ShouBuRecordDto(
            lgtd = binding.lgtd.text.toString(), // 泵站经度
            lttd = binding.lttd.text.toString(), // 泵站纬度
            gcbh = binding.gcbh.text.toString(), // 工程编号
            gqmc = binding.gqmc.text.toString(), // 灌区名称
            sztcdm = binding.sztcdm.text.toString(), // 所在团场
            sbmc = binding.sbmc.text.toString(), // 首部名称
            szqdmc = binding.szqdmc.text.toString(), // 所在渠道名称
            sblx = binding.sblx.text.toString(), // 首部类型
            gcdb = binding.gcdb.text.toString(), // 工程等别
            zyjzwjb = binding.zyjzwjb.text.toString(), // 主要建筑物级别
            zjll = binding.zjll.text.toString(), // 装机流量(m3/s)
            sjyc = binding.sjyc.text.toString(), // 设计扬程(m)
            zjgl = binding.zjgl.text.toString(), // 装机功率(kW)
            sbsl = binding.sbsl.text.toString(), // 水泵数量(台)
            glfmj = binding.glfmj.text.toString(), // 管理房面积(㎡)
            gdcd = binding.gdcd.text.toString(), // 管道长度(m)
            gcrw = binding.gcrw.text.toString(), // 工程任务
            kzggmj = binding.kzggmj.text.toString(), // 控制灌溉面积(亩)
            ngPsl = binding.ngPsl.text.toString(), // 年供、排水量(m3)
            trsysj = binding.trsysj.text.toString(), // 投入使用时间(年月)
            gjsj = binding.gjsj.text.toString(), // 改建时间(年月)
            gldwmc = binding.gldwmc.text.toString(), // 管理单位名称
            note = binding.note.text.toString() // 更新备注
        )
        dto.state = "1"
        dto.type = dataType
        dto.inputAddvcd = loginVo?.depId
        dto.inputBy = loginVo?.id
        val picPath = photos.joinToString(",", transform = {
            it.id!!
        })
        dto.picPath = picPath
        waterViewModel.insertShouBuRecord(dto)

    }

    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }
    var dataType = "ADD"//数据操作类型
    private fun getData() {
        val operationType = intent.getStringExtra("operationType")
        val guid = intent.getStringExtra("guid")
        val type = intent.getStringExtra("type")
        val state = intent.getStringExtra("state")
        //审核详情
        if ("opinion" == operationType) {
            waterViewModel.getAfterShouBuParam(guid,type)
            if( state!!.contains("待")){
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            }
            else  if(state.contains("已")){
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            }
            else{
                dataType = "UPDATE"
                binding.btnSave.visibility = View.VISIBLE
                binding.llReason.visibility = View.VISIBLE
                binding.rlUpload.isEnabled = true
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))
            }

        } else {
            dataType = "ADD"
            waterViewModel.getShouBuBasic(intent.getStringExtra("id")!!)
            binding.llReason.visibility = View.GONE
            binding.rlUpload.isEnabled = true
            binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))

        }



    }


    var title = ""
    override fun initView() {
        DictionariesManager.getShouBuDictionaries()
        title = "${intent.getStringExtra("title")}"
        setTitle(
            title = title,
            isBack = true,
            tvRightRes1 = R.string.str_location,
            tvRight1Action = {
                val intent = Intent(this, MapActivity::class.java)
                intent.putExtra("title", title)
                val mapList = mutableListOf(
                    MapDataBean(
                        name = title,
                        lgtd = binding.lgtd.text.toString(),
                        lttd = binding.lttd.text.toString(),
                    )
                )
                intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
                startActivity(intent)
            }

        )
        initAdapter()
    }
    private fun initAdapter() {
        val map = hashMapOf(RvSpacesItemUtils.RIGHT_DECORATION to DisplayUtil.dip2px(this, 10f))
        binding.rvFile.addItemDecoration(RvSpacesItemUtils(map))



        binding.rvFile.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        selectPhotoAdapter = SelectPhotoAdapter(this, listener = {


        }, close = {
            photos.removeAt(it)
            selectPhotoAdapter?.notifyDataSetChanged()
        }, datas = photos)
        binding.rvFile.adapter = selectPhotoAdapter
    }

    override fun setContentView() {
        binding = ActivityShoubuItemDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null
    private fun startLocation() {
        Log.d(TAG, "startLocation: ===========")
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                val longitude = "${p0?.longitude}"
                val latitude = "${p0?.latitude}"
                Log.d(TAG, "onLocationChanged: ${longitude} ${latitude}")
                binding.lttd.setText(latitude)
                binding.lgtd.setText(longitude)

            }

        })

        mLocationOption = AMapLocationClientOption()
        val option = AMapLocationClientOption()
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);

        if (null != mLocationClient) {
            mLocationClient?.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient?.stopLocation()
            mLocationClient?.startLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }


}